<?php

namespace Home\Controller;

use Think\Controller;
use Org\Util\Juhe;
/**
 * 购车控制器
 * @author zhangwei
 */
class CartController extends HomeController {
    /**
     * 创建订单
     * @param type $addressradio
     * @param type $remark
     */
    public function createOrder($addressradio = "", $remark = "",$amount="") {
        //清除立即购买商品
        if($amount==""||$amount==null){
            $amount=0;
        }
        $userid = session('userid');
        $orderNo = "O" .$userid.NOW_TIME;
        $orderPrice = 0;
        $smslist=":";
        $cartPro = D('product');
        $sqlpro = "select a.pid,a.pnum,b.name,b.quantity,b.picurlarray,b.price from gr_cart a,gr_product b where a.uid = $userid and "
                . "a.pid = b.id and a.status = 1";
        $cartPros = $cartPro->query($sqlpro);
        $protable = M('product');
        $orderGoods = M("order_goods");
        for ($i = 0; $i < count($cartPros); $i++) {
            /**
             * 多买多优惠 start
             * @param pid
             * @author Scor
             */
            $isActivity=M('activity_more_buy')->where('id='.$cartPros[$i]['pid'])->select();
            if(count($isActivity)>0){
                if($cartPros[$i]['pnum']>=$isActivity[0]['num1']&&$isActivity[0]['num1']>0&&$isActivity[0]['price1']>0){
                    $cartPros[$i]['price']=$isActivity[0]['price1'];
                    if($cartPros[$i]['pnum']>=$isActivity[0]['num2']&&$isActivity[0]['num2']>0&&$isActivity[0]['price2']>0){
                        $cartPros[$i]['price']=$isActivity[0]['price2'];
                    }
                }
            }
            /**
             * 多买多优惠 end
             */
            $cartPros[$i]['sumproprice'] = $cartPros[$i]['pnum'] * $cartPros[$i]['price'];
            $orderPrice += $cartPros[$i]['pnum'] * $cartPros[$i]['price'];
            $order_goods_data[] = array(
                'orderid' => $orderNo,
                'pid' => $cartPros[$i]['pid'],
                'price' => $cartPros[$i]['price'],
                'cartnum' => $cartPros[$i]['pnum'],
                'expectcartnum' => $cartPros[$i]['pnum'],
                'totalprice' => $cartPros[$i]['sumproprice'],
                'expecttotalprice' => $cartPros[$i]['sumproprice']
            );
            $smslist=$smslist.get_goods_name($cartPros[$i]['pid'])."*".$cartPros[$i]['pnum'].'个/';
            $proInventory = $protable->where(array('id'=>$cartPros[$i]['pid']))->getField('inventory');
            $proInventory -= $cartPros[$i]['pnum'];
            $proData = array('inventory'=>$proInventory);
            $protable->where(array('id'=>$cartPros[$i]['pid']))->save($proData);
        }
        $orderGoods->addAll($order_goods_data);
        $addr = M('addr')->where(array('id' => $addressradio, 'status' => 1))->find();
        $orderData = array(
            'orderid' => $orderNo,
            'amount' => $orderPrice,
            'expectamount' => $orderPrice,
            'uid' => $userid,
            'createDate' => NOW_TIME,
            'toName' => $addr['name'],
            'toProvince' => $addr['province'],
            'toCity' => $addr['city'],
            'toArea' => $addr['area'],
            'toStreet' => $addr['street'],
            'toPhone' => $addr['phone'],
            'remark' => $remark,
            'lastupdate' => NOW_TIME,
            'toShopName' => $addr['shopname']
        );
        if($cartPros[0]["price"]<=0){
            \Think\Log::record('<-------'.$cartPros,'ERR1001');
            \Think\Log::record($order_goods_data.'----->','ERR1001');
            $orderData['amount']=0;
            $orderData['status']=4000;
        }else{
            $detail="订单".$orderNo;
            $act="decre";
            R("Activity/amountFlow",array($amount,$detail,$act));
            $amountData['id']=$userid;
            D("buyers")->where(array('id'=>$userid))->setDec('amount',$amount);
            $orderData['useamount']=$amount;
            $orderData['amount']=$orderPrice-$amount;
            
        }
        M("order")->add($orderData);
        if($cartPros[0]["price"]>0){
              M('cart')->where(array('uid'=>session('userid')))->delete();
              // 短信发送功能
              $smslist=$smslist."备注：".$remark;
              $labelTable=D('config');
              $where['name']='TXMOBILE';
              $labellist=$labelTable->where($where)->getfield('value');
              $str= explode("\n", $labellist);
              $arr=array();
              foreach ($str as $value){
                  $arr2=explode(":", $value);
                  if($arr2[0]==""||$arr2[0]==" "||$arr2[0]==null){

                  }else{
                      $arr[$arr2[0]]=trim($arr2[1]);
                  }
              }
              foreach ($arr as $value){
                  $mobile=$value;
                  $JUHE= new Juhe();
                  $tpl_id=4529;
                  $tpl_value = "#price#=" . $orderPrice . "&#list#=" . $smslist;
                  $JUHE->sendSMS($mobile, $tpl_id, $tpl_value);
              }
        }
        $this->redirect('Center/history');
    }
    /**
     *检查余额
     */
    public function checkAmount(){
        $userid = session('userid');
        $amount=I("amount");
        $flag =1;
        $buyer = M('buyers');
        $res = $buyer->where(array('id'=>$userid))->find();
        if($res["amount"]==$amount){
            $flag=0;
        }
       $this->ajaxReturn($flag);
    }
    /**
     *检查库存
     */
    public function checkStore(){
        $userid = session('userid');
        $flag ="";
        $prostable = M('product');
        $carttable = M('cart');
        $cartPros = $carttable->where(array('uid'=>$userid))->select();
        for ($i=0; $i<count($cartPros);$i++){
            $pro = $prostable->where(array('id'=>$cartPros[$i]['pid']))->find();
            if($pro['status'] == 1){

            }else{
                $flag.= $pro['name']."已下架，已从购物车删除;";
                $carttable->where(array('uid'=>$userid,'pid'=>$cartPros[$i]['pid']))->delete();
                continue;
            }
            if($pro['inventory']==0){
                $flag.= $pro['name']."库存不足，已从购物车删除;";
                $carttable->where(array('uid'=>$userid,'pid'=>$cartPros[$i]['pid']))->delete();
            }else if ($pro['inventory'] < $cartPros[$i]['pnum']){
                $flag.= $pro['name']."仅剩".$pro['inventory']."件;";
                $data = array('pnum'=>$pro['inventory']);
                $carttable->where(array('uid'=>$userid,'pid'=>$cartPros[$i]['pid']))->save($data);
            }

        }
        $this->ajaxReturn($flag);
    }

    /**
     * 新增地址
     */
    public function addAddr() {
        if($_REQUEST['id'] == ""|| $_REQUEST['id'] == null){
            $code = M('addr')->add(array('uid' => session('userid'), 'name' => $_REQUEST['realName'], 'shopName' => $_REQUEST['shopName'],
                'province' => $_REQUEST['province'], 'city' => $_REQUEST['city'], 'area' => $_REQUEST['area'], 'street' => $_REQUEST['street'],
                'phone' => $_REQUEST['phone'], 'createdate' => NOW_TIME, 'lastupdate' => NOW_TIME));
        }else{
            $code = M('addr')->where(array('id'=>$_REQUEST['id']))->save(array( 'name' => $_REQUEST['realName'], 'shopName' => $_REQUEST['shopName'],
                'city' => $_REQUEST['city'], 'area' => $_REQUEST['area'], 'street' => $_REQUEST['street'],
                'phone' => $_REQUEST['phone'], 'lastupdate' => NOW_TIME));
        }
        $this->ajaxReturn($code);
    }

    /**
     * 删除地址
     */
    public function delAddr() {
        $addrid = $_REQUEST['addrid'];
        $map = array('id' => $addrid);
        $data = array('status' => -1);
        $code = M('addr')->where($map)->save($data);
        $this->ajaxReturn($code);
    }

    /**
     * 修改数量
     */
    public function changeNum() {
        $pid = $_REQUEST['pid'];
        $pnum = $_REQUEST['num'];
        $proInventory = M('product')->where(array('id'=>$pid))->getField('inventory');
        if ($pnum > $proInventory){
            $this->ajaxReturn($proInventory);
        }
        $userid = session('userid');
        $data = array('pnum' => $pnum);
        $code = M('cart')->where(array('uid' => $userid, 'pid' => $pid))->save($data);
        $this->ajaxReturn(-1);
    }

    /**
     * 删除商品
     */
    public function delPro() {
        $pid = $_REQUEST['pid'];
        $userid = session('userid');
        $code = M('cart')->where(array('uid' => $userid, 'pid' => $pid))->delete();
        $this->ajaxReturn($code);
    }

}
